package zy.blue7.gui;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @Author: blue7
 * @Date: 2022/2/24 19:45
 * @Version 1.0
 * @Description
 */
public class NettyClient {

    private static ChannelFuture channelFuture=null;
    private static Channel  channel =null;

    public static  void  start() throws InterruptedException {

        //1.启动类
        channel= new Bootstrap()
                // 2.添加 EventLoop
                .group(new NioEventLoopGroup())
                //3. 选择客户端 channel实现
                .channel(NioSocketChannel.class)
                //4.添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override // todo 在建立链接的时候调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                //5.连接到服务器
                .connect(new InetSocketAddress("localhost", 8080))
                .sync() //todo 阻塞方法，知道链接建立
                .channel();
                // 6.向服务器发送数据
//                .writeAndFlush("hello world");
    }

    public static void  send(String str){
        channel.writeAndFlush(str);
    }
}
